<?php
// +----------------------------------------------------------------------------
// | Tke团队版权所属 [三十年河东三十年河西,莫欺少年穷.!]
// +----------------------------------------------------------------------------
// | Copyright (c) 2014 http://www.itdaodan.com All rights reserved.
// +----------------------------------------------------------------------------
// | Author: fzh
// +----------------------------------------------------------------------------

namespace Admin\Model;
use Admin\Model\BaseModel;
/**
 * @todo 招商会店铺模型
 */

class BusinessShopModel extends BaseModel {

    /* 自动验证规则 */
    protected $_validate = array(
        array('activity_id', 'gtNumber', '请选择活动', self::MUST_VALIDATE, 'callback', self::MODEL_BOTH),
        array('business_category_id', 'gtNumber', '请选择品类', self::MUST_VALIDATE, 'callback', self::MODEL_BOTH),
        array('business_shop_name', 'require', '店铺名称不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('business_shop_name', '1,40', '店铺名称长度不能超过40个字符', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
    	array('business_shop_number', 'number', '展位数量必须为数字', self::EXISTS_VALIDATE , 'regex', self::MODEL_UPDATE),
        array('business_shop_year', '0,1', '请正确选择是否为全年', self::EXISTS_VALIDATE , 'in', self::MODEL_UPDATE),
        array('business_shop_owner_name', 'require', '店主姓名不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('business_shop_owner_name', '1,10', '店主姓名长度不能超过10个字符', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
        array('business_shop_mobile', 'require', '店铺电话不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('business_shop_mobile', '1,11', '店铺电话长度不能超过11个字符', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
    );

    /* 自动完成规则 */
    protected $_auto = array(
        array('business_shop_number', 0, self::MODEL_INSERT),
        array('business_shop_year', 0, self::MODEL_INSERT),
    	array('create_time', NOW_TIME, self::MODEL_INSERT),
    	array('update_time', NOW_TIME, self::MODEL_BOTH),
    	array('uid', UID, self::MODEL_INSERT),
    	array('status', '1', self::MODEL_INSERT),
    );

    /**
     * 新增或更新一个店铺
     * @return boolean fasle 失败 ， int  成功 返回店铺ID
     * @author fzh
     */
    public function update(){
        /* 获取数据对象 */
    	$data = $this->create($_POST);
        if(empty($data)){
            return false;
        }
        /* 添加或更新数据 */
        if(empty($data['business_shop_id'])){ //新增数据
            $business_shop_id = $this->add();
            if(!$business_shop_id){
                $this->error = '新增店铺出错！';
                return false;
            }
        } else { //更新数据
            $status = $this->save(); //更新基础内容
            if(false === $status){
                $this->error = '更新店铺出错！';
                return false;
            }else{
            	$business_shop_id = $data['business_shop_id'];
            }
        }
        //内容添加或更新完成
        return $business_shop_id;
    }

    
    
    /**
     * @todo 店铺详情
     * @param int $business_shop_id 店铺id
     * @param string $field 查询字段
     * @return false|array
     * @author fzh
     */
    public function businessShopShow($business_shop_id=0,$field=''){
    	//获取数据
    	$business_shop_id = (int)$business_shop_id;
    	if($business_shop_id == 0){
    		$this->error = '请正确操作';
    		return false;
    	}
    	$map = array();//初始化查询条件
    	//查询条件
    	$map['business_shop_id'] = $business_shop_id;
    	$map['status'] = array('gt',-1);
    	//返回值
    	return $this->where($map)->field($field)->find();
    }
    
    /**
     * @todo 调取店铺列表
     * @author fzh
     */
    public function getShopList($map = array(),$field='',$orderby='sort desc,shop_id desc'){
    	return $this->where($map)->field($field)->order($orderby)->select();
    }
    
    /**
     * @todo 导入店铺
     * @param int $file_id 文件id
     * @param int $activity_id 活动id
     * @param int $business_category_id 品类id
     * @author fzh
     */
    public function importiShop($file_id,$activity_id,$business_category_id){
        $file_id = (int)$file_id;
        $activity_id = (int)$activity_id;
        $business_category_id = (int)$business_category_id;
        
        if($file_id == 0){
            $this->error = '文件不存在1';
            return false;
        }
        if($activity_id == 0){
            $this->error = '请选择活动';
            return false;
        }
        if($business_category_id == 0){
            $this->error = '请选择品类';
            return false;
        }
        
        $map = array();
        $map['id'] = $file_id;
        $file_info = M('File')->where($map)->find();
        if(empty($file_info)){
            $this->error = '文件不存在2';
            return false;
        }
        
        $file_url = C('DOWNLOAD_UPLOAD.rootPath').$file_info['savepath'].$file_info['savename']; //文件地址
        
        set_time_limit (0);//程序执行时间
        //导入phpExcel核心类
        import( "Common.Msj.PHPExcel.PHPExcel.IOFactory" ,'' ,'.php' );
        $objReader = \PHPExcel_IOFactory::createReader('CSV');
        $objReader->setDelimiter(',');//默认的分隔符
        $objReader->setInputEncoding('GBK');//默认的输入字符集
        if(!$objReader->canRead($file_url)){
            $this->error = '生成失败! 无法读取该文件数据';
            return false;
        }
        $objPHPExcel = $objReader->load ($file_url);
        $sheet = $objPHPExcel->getSheet (0);
        $highestRow = $sheet->getHighestRow (); // 取得总行数
    
        //添加判断 导入总用户数不得大于3000千条
        if($highestRow > 3001){
            $this->error = '导入用户总数不得大于3000条';
            return false;
        }
        if($highestRow < 2){
            $this->error = '空文件';
            return false;
        }
    
        $data_add = array(); //添加数据初始化
        $arr = array(); //手机号数组初始化
        $error_num = 0; //失败总数
    
        for($j = 2; $j <= $highestRow; $j ++) {
            
            $shop = trim((string)$objPHPExcel->getActiveSheet()->getCell("A" .$j)->getValue());//店铺
            $name = trim((string)$objPHPExcel->getActiveSheet()->getCell("B" .$j)->getValue());//店铺
            $mobile = trim((string)$objPHPExcel->getActiveSheet()->getCell("C" .$j)->getValue());//店铺
            
            if(empty($shop) || strlen($shop)>40 || empty($name) || strlen($name)>10 || empty($mobile) || strlen($mobile)>11 || !preg_match("/^1[3-8][0-9]{9}$/", $mobile)){
                $error_num = $error_num + 1;
                continue;
            }
            
            
            $data_add[] = array(
                'business_shop_name'=>$shop,
                'business_shop_owner_name'=>$name,
                'business_shop_mobile'=>$mobile,
                'activity_id'=>$activity_id,
                'business_category_id'=>$business_category_id,
                'business_shop_number'=>0,
                'business_shop_year'=>0,
                'uid'=>UID,
                'status'=>1,
                'create_time'=>NOW_TIME,
                'update_time'=>NOW_TIME
            ); 
        }
        if(empty($data_add)){
            $this->error = '空文件';
            return false;
        }
        if(M('business_shop')->insertIgnoreAddAll($data_add) === false){
            $this->error = '导入失败，请重试';
            return false;
        }
    
        $result = array(
            'count_num' => $highestRow - 1,
            'error_num' => $error_num,
            'success_num' => $highestRow - 1 - $error_num,
        );
        return $result;
    }
    
    /**
     * @todo 返回主键
     * @see \Think\Model::getPk()
     * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
     */
    public function getPk(){
    	return 'business_shop_id';
    }
    
    
    /**
     * @todo 验证大于0的数字
     */
    public function gtNumber($pic_id){
        $pic_id = (int)$pic_id;
        if($pic_id <= 0){
            return false;
        }
    
    }
   
}
